package com.guigu.buy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guigu.buy.pojo.SysMenu;
import com.guigu.buy.pojo.SysRole;
import com.guigu.buy.pojo.SysUser;
import com.guigu.buy.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.management.relation.Role;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author com.guigu
 * @since 2024-05-15
 */

@CrossOrigin
@RestController
@RequestMapping("/buy/sysRole")
public class SysRoleController {
    @Autowired
    private ISysRoleService sysRoleService;
    @RequestMapping("/getAllRole")
    @ResponseBody
    private List<Map<String,Object>> getAllRole(){
        List<Map<String,Object>> list =new ArrayList<>();
        QueryWrapper<SysRole> qw=new QueryWrapper<>();
        qw.eq("status",0);
        List<SysRole> rolelist = sysRoleService.list(qw);
        if (rolelist.size()>0){
            for (SysRole role:rolelist){
                Map<String,Object> map=new LinkedHashMap<>();
                map.put("id",role.getId());
                map.put("roleName",role.getRoleName());
                map.put("descn",role.getDescn());
                map.put("status",role.getStatus());
                map.put("rolecode",role.getRoleCode());
                map.put("children",sysRoleService.getmenuList(role.getId()));
                list.add(map);
            }
        }
        System.out.println(list);
        return list;
    }
    @PostMapping("/add")
    public String add(@RequestBody SysRole role) {
        // 默认正常
        role.setStatus("0");
        role.setRoleCode(2);
        boolean flag = sysRoleService.save(role);
        if (flag){
            return "ok";
        }else {
            return "no";
        }
    }
    @RequestMapping("/getRoleById/{id}")
    public SysRole getRoleById(@PathVariable Integer id){
        QueryWrapper<SysRole> qw = new QueryWrapper<>();
        System.out.println("id:"+id);
        qw.eq("id",id);
        SysRole role=sysRoleService.getOne(qw);
        return role;
    }
    @RequestMapping("/deleteRole/{id}")
    public Object deleteRole(@PathVariable Long id) {
        // 从数据库中获取角色信息
        SysRole role = sysRoleService.getById(id);
        if (role != null) {
            // 将角色的状态改为1，代表删除
            role.setStatus("1");
            // 更新角色信息
            sysRoleService.updateById(role);
        }
        // 返回相应的结果
        return true;
    }
    @RequestMapping("/updateRoleById")
    public boolean updateUserById(@RequestBody SysRole role){
        QueryWrapper<SysRole> qw = new QueryWrapper<>();
        qw.eq("id",role.getId());
        boolean flag =sysRoleService.update(role,qw);
        return flag;
    }

}
